package com.leetcode.partition10;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2021/12/11 11:37
 */
@SuppressWarnings("all")
public class LC911在线选举 {

    public static void main(String[] args) {
        int[] persons = {0, 1, 1, 0, 0, 1, 0}, times = {0, 5, 10, 15, 20, 25, 30};
        TopVotedCandidate topVotedCandidate = new TopVotedCandidate(persons, times);
        System.out.println(topVotedCandidate.q(20));
    }

    private static class TopVotedCandidate {

        private List<int[]> tops = new ArrayList<>();

        public TopVotedCandidate(int[] persons, int[] times) {
            //记录当前时刻的最大票数
            int maxVote = 0;
            Map<Integer, Integer> voteMap = new HashMap<>();
            for (int i = 0; i < times.length; i++) {
                int vote = voteMap.getOrDefault(persons[i], 0);
                voteMap.put(persons[i], vote + 1);
                if (maxVote <= vote + 1) {
                    maxVote = vote + 1;
                    tops.add(new int[]{times[i], persons[i]});
                }
            }
        }

        public int q(int t) {
            //二分查找，找到小于等于t的那个时间的当选人
            int left = 0, right = tops.size() - 1;
            while (left < right) {
                int mid = (left + right + 1) >>> 1;
                if (tops.get(mid)[0] > t) right = mid - 1;
                else left = mid;
            }
            return tops.get(left)[1];
        }
    }
}
